using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using Microsoft.Win32;
using System.Xml;

namespace FileBackupServiceCSHP
{
    partial class BackupService : ServiceBase
    {
        private string _xmlpath;
        private string _elapseds;
        private System.Timers.Timer timer2;

        public BackupService()
        {
            InitializeComponent();
            timer2 = new System.Timers.Timer();
            timer2.Interval = 10000;
            timer2.Elapsed += new System.Timers.ElapsedEventHandler(timer2_Elapsed);
        }

        void timer2_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            timer1_Tick(sender, (EventArgs)e);
        }

        protected override void OnStart(string[] args)
        {
            _xmlpath = Registry.LocalMachine.OpenSubKey("SOFTWARE").OpenSubKey("BNProd").OpenSubKey("FileBackUp").GetValue("projectsxml").ToString();
            _elapseds = Registry.LocalMachine.OpenSubKey("SOFTWARE").OpenSubKey("BNProd").OpenSubKey("FileBackUp").GetValue("elapse").ToString();
            timer2.Interval = double.Parse(_elapseds);
            timer2.Start();
        }

        protected override void OnStop()
        {
            // TODO: Add code here to perform any tear-down necessary to stop your service.
        }

        public static void Main()
        {
            System.ServiceProcess.ServiceBase[] ServicesToRun;
            ServicesToRun = new System.ServiceProcess.ServiceBase[] { new BackupService() };
            System.ServiceProcess.ServiceBase.Run(ServicesToRun);
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            timer2.Stop();
            bool save = false;
            try
            {
                //load all projects
                XmlDocument doc = new XmlDocument();
                doc.Load(_xmlpath);
                
                XmlNodeList projects = doc.SelectNodes("//project[action/@time!='request']");
                //check to see if any are overdue for execution
                foreach (XmlElement project in projects)
                {
                    FileFolderNavigator.ProjectElement elem = new FileFolderNavigator.ProjectElement(project);
                    DateTime last = DateTime.Parse(elem.Action.Last);
                    double days = double.Parse(elem.Action.Days);
                    FileFolderNavigator.FolderBackup.ExecuteProjectCheckTime(elem);
                }
                if (save)
                {
                    doc.Save(_xmlpath);
                }
            }
            catch
            {
                //log exception
            }
            timer2.Start();
        }
    }
}
